package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WxAesUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.FormSub;
import com.ruoyi.system.domain.OrderDetail;
import com.ruoyi.system.domain.UserLogin;
import com.ruoyi.system.domain.vo.AlPayVo;
import com.ruoyi.system.domain.vo.WxPayVo;
import com.ruoyi.system.mapper.FormSubMapper;
import com.ruoyi.system.mapper.OrderDetailMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.tools.HttpUtils;
import com.ruoyi.web.controller.domain.EnterpriseInfo;
import com.ruoyi.web.controller.service.IEnterpriseInfoService;
import com.ruoyi.web.controller.service.SseServer;
import com.ruoyi.web.controller.tool.aliTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.annotation.Transient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 用户登录记录 控制器
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class UserLoginController extends BaseController {
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    public WeChatPayService weChatPayService;
    @Autowired
    private AlipayService alipayService;
    @Resource
    private SseServer sseServer;
    @Value("${alipay.callback}")
    private String aliPayCallback;

    @Value("${wx.pay.redirectUrl}")
    private String redirectUrl;
    @Value("${wx.pay.callback}")
    private String wxPayCallback;
    @Value("${wx.pay.jsapiCallback}")
    private String wxJsapiPayCallback;
    @Value("${alipay.appCode}")
    private String appCode;
    @Value("${wx.pay.key}")
    private String v3Key;

    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private FormSubMapper formSubMapper;
    @Autowired
    private IEnterpriseInfoService enterpriseInfoService;
    @Autowired
    private ISysDictTypeService dictTypeService;



    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Anonymous
    public AjaxResult login(String userKey, String code) {
        String openId = "";
        // 查询是否存在该用户
        if (StringUtils.isNotEmpty(userKey)) {
            // 查询enterprise_info表中是否存在该userKey
            EnterpriseInfo enterpriseInfo = enterpriseInfoService.selectEnterpriseInfoByShortLink(userKey);
            if (Objects.isNull(enterpriseInfo)) {
                return error("登录失败,无效的链接");
            }
            UserLogin userLogin = userLoginService.selectUserLoginByUserKey(userKey);
            if (Objects.isNull(userLogin)) {
                // 新用户，创建登录记录
                userLogin = new UserLogin();
                userLogin.setUserKey(userKey);
                userLogin.setToken(UUID.fastUUID().toString());
                userLogin.setCreateTime(new Date());
                // 根据 code 获取 openid
                if(StringUtils.isNotEmpty(code)){
                    openId = weChatPayService.getOpenIdByCode(code);
                    userLogin.setOpenid(openId); // 存入 openid
                }
                userLoginService.insertUserLogin(userLogin);
            }else if (StringUtils.isEmpty(userLogin.getOpenid())) {
                openId = weChatPayService.getOpenIdByCode(code);
                userLogin.setOpenid(openId);
                userLogin.setUserKey(userKey);
                userLoginService.updateUserLogin(userLogin);
            }
            return AjaxResult.success("登录成功", userLogin);
        }
        // 新用户，创建登录记录
        UserLogin userLogin = new UserLogin();
        if(StringUtils.isNotEmpty(code)){
            openId = weChatPayService.getOpenIdByCode(code);
            userLogin.setOpenid(openId);
        }
        userLogin.setUserKey(userKey);
        userLogin.setToken(UUID.fastUUID().toString());
        userLogin.setCreateTime(new Date());
        userLoginService.insertUserLogin(userLogin);
        return AjaxResult.success("登录成功", userLogin);
    }

    //wxh5 支付
    @PostMapping("/wxPay")
    @Anonymous
    @Transient
    public AjaxResult wechatPayOrder(@Validated @RequestBody WxPayVo wxPayVo, HttpServletRequest request) throws Exception {
        //支付订单号
        String orderId = wxPayVo.getOrderNumber();
        OrderDetail orderDetail = orderDetailMapper.selectOrderDetailByOrderNumber(orderId);
        if (Objects.isNull(orderDetail)) {
            return error("订单不存在");
        }
        if (!orderDetail.getStatus().equals("0")) {
            return error("订单状态异常");
        }
        log.info("支付订单号:{}", orderId);
        String ip = HttpUtils.getIpAddress(request);//客户端ip
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));//获取第一个ip
        }
        log.info("支付客户端ip:{}", ip);
        // 根据orderType查询字典获取支付金额
        String orderType = orderDetail.getOrderType();
        if (StringUtils.isEmpty(orderType)) {
            return error("订单类型不能为空");
        }
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("h5_sys_orderprice");
        // 从字典服务获取金额
        SysDictData dictData = dictDataService.selectDictDataList(sysDictData)
                .stream()
                .filter(dict -> orderType.equals(dict.getDictValue()))
                .findFirst()
                .orElse(null);

        if (Objects.isNull(dictData)) {
            return error("未找到对应的订单金额配置");
        }
        BigDecimal amount;
        try {
            amount = new BigDecimal(dictData.getDictLabel()).divide(BigDecimal.valueOf(100));
        } catch (NumberFormatException e) {
            log.error("订单金额配置格式错误", e);
            return error("订单金额配置错误");
        }

        // 使用查询到的金额替换原有的固定金额
        String url = weChatPayService.wxH5Pay(orderDetail.getBusinessName(), orderId, amount.intValue(), ip, wxPayCallback);
        orderDetailMapper.updateAmountById(convertToCents(amount.intValue()), amount, orderDetail.getId());
        if (StringUtils.isEmpty(url)) {
            return AjaxResult.error("微信支付失败,请稍后重试");
        }
        try {
            String newReurl = redirectUrl + "?orderNum=" + orderId;
            url = url + "&redirect_url=" + URLEncoder.encode(newReurl, "utf-8");
            log.info("跳转地址:{}", url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.info("跳转地址获取失败");
            return AjaxResult.error(url);
        }
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        map.put("tel", orderDetail.getTel());
        map.put("orderId", orderId);
        sseServer.sendAllMessage();
        return AjaxResult.success(map);
    }

    public static int convertToCents(int amountInYuan) {
        return amountInYuan * 100;
    }

    //支付宝h5支付
    @PostMapping("/aliPay")
    @Anonymous
    @Transient
    public AjaxResult alipayOrder(@Validated @RequestBody AlPayVo alPayVo, HttpServletRequest request) throws Exception {
        //支付订单号
        String orderId = alPayVo.getOrderNumber();
        OrderDetail orderDetail = orderDetailMapper.selectOrderDetailByOrderNumber(orderId);
        if (Objects.isNull(orderDetail)) {
            return error("订单不存在");
        }
        if (!orderDetail.getStatus().equals("0")) {
            return error("订单状态异常");
        }
        log.info("支付宝支付订单号:{}", orderId);
        String ip = HttpUtils.getIpAddress(request);
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
        log.info("支付客户端ip:{}", ip);

        // 根据orderType查询字典获取支付金额
        String orderType = orderDetail.getOrderType();
        if (StringUtils.isEmpty(orderType)) {
            return error("订单类型不能为空");
        }
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("h5_sys_orderprice");
        // 从字典服务获取金额
        SysDictData dictData = dictDataService.selectDictDataList(sysDictData)
                .stream()
                .filter(dict -> orderType.equals(dict.getDictValue()))
                .findFirst()
                .orElse(null);

        if (Objects.isNull(dictData)) {
            return error("未找到对应的订单金额配置");
        }
        BigDecimal amount;
        try {
            amount = new BigDecimal(dictData.getDictLabel()).divide(BigDecimal.valueOf(100));
        } catch (NumberFormatException e) {
            log.error("订单金额配置格式错误", e);
            return error("订单金额配置错误");
        }
        //调用支付宝支付服务
        String url = alipayService.createH5Pay(orderDetail.getBusinessName(), orderId, amount.multiply(BigDecimal.valueOf(100)).intValue(), ip, aliPayCallback);
        orderDetailMapper.updateAmountById(convertToCents(amount.intValue()), amount, orderDetail.getId());
        if (StringUtils.isEmpty(url)) {
            return AjaxResult.error("支付宝支付失败,请稍后重试");
        }
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        map.put("tel", orderDetail.getTel());
        map.put("orderId", orderId);
        sseServer.sendAllMessage();
        return AjaxResult.success(map);
    }

    /**
     * 微信H5支付回调通知
     */
    @PostMapping("/wxPayNotify")
    @Anonymous
    public String wxH5PayNotify(HttpServletRequest request) {
        log.info("微信支付回调通知开始");
        try {
            // 获取通知数据
            String xmlData = HttpUtils.readData(request);
            log.info("微信支付回调通知数据：{}", xmlData);

            // 验证签名
            if (!weChatPayService.verifyNotify(xmlData)) {
                log.error("微信支付回调通知签名验证失败");
                return weChatPayService.responseFailure("签名验证失败");
            }

            // 解析订单号
            Map<String, String> notifyMap = weChatPayService.parseNotifyData(xmlData);
            String orderNumber = notifyMap.get("out_trade_no");
            String transactionId = notifyMap.get("transaction_id");

            // 处理订单
            OrderDetail orderDetail = orderDetailMapper.selectOrderDetailByOrderNumber(orderNumber);
            if (orderDetail != null && "0".equals(orderDetail.getStatus())) {
                orderDetail.setStatus("1"); // 设置为已支付
                orderDetail.setTransactionId(transactionId);
                orderDetail.setPayTime(new Date());
                orderDetailMapper.updateOrderDetail(orderDetail);
                log.info("订单{}支付成功，微信交易号：{}", orderNumber, transactionId);
            }
            sseServer.sendAllMessage();
            return weChatPayService.responseSuccess();
        } catch (Exception e) {
            log.error("微信支付回调通知处理异常", e);
            return weChatPayService.responseFailure("处理失败");
        }
    }

    /**
     * 微信jsapi支付回调通知
     */
    @PostMapping("/wxJsapiPayNotify")
    @Anonymous
    public String wxPayNotify(@RequestBody JSONObject data) {
        log.info("微信支付回调通知开始");
        try {
            // 获取通知数据
            log.info("微信支付回调通知数据：{}", data);
            // 解析订单号
            WxAesUtil wxAesUtil = new WxAesUtil(v3Key.getBytes());
            JSONObject jsonRe = data.getJSONObject("resource");
            String re = wxAesUtil.decryptToString(jsonRe.getString("associated_data").getBytes(), jsonRe.getString("nonce").getBytes(), jsonRe.getString("ciphertext"));
            JSONObject notifyMap = JSONObject.parseObject(re);
            String orderNumber = notifyMap.getString("out_trade_no");
            String transactionId = notifyMap.getString("transaction_id");
            // 处理订单
            OrderDetail orderDetail = orderDetailMapper.selectOrderDetailByOrderNumber(orderNumber);
            if (orderDetail != null && "0".equals(orderDetail.getStatus())) {
                orderDetail.setStatus("1"); // 设置为已支付
                orderDetail.setTransactionId(transactionId);
                orderDetail.setPayTime(new Date());
                orderDetailMapper.updateOrderDetail(orderDetail);
                log.info("订单{}支付成功，微信交易号：{}", orderNumber, transactionId);
            }
            sseServer.sendAllMessage();
            return weChatPayService.responseSuccess();
        } catch (Exception e) {
            log.error("微信支付回调通知处理异常", e);
            return weChatPayService.responseFailure("处理失败");
        }
    }

    /**
     * 支付宝支付回调通知
     */
    @PostMapping("/aliPayNotify")
    @Anonymous
    public String aliPayNotify(HttpServletRequest request) {
        log.info("支付宝支付回调通知开始");
        try {
            // 获取支付宝POST过来的信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            log.info("支付宝支付回调通知参数：{}", params);

            // 验证签名
            if (!alipayService.verifyNotify(params)) {
                log.error("支付宝支付回调通知签名验证失败");
                return "failure";
            }

            // 判断是否支付成功
            String tradeStatus = params.get("trade_status");
            if (!"TRADE_SUCCESS".equals(tradeStatus)) {
                log.info("支付宝支付未成功，状态：{}", tradeStatus);
                return "success";
            }

            // 获取订单信息
            String orderNumber = params.get("out_trade_no");
            String transactionId = params.get("trade_no");

            // 处理订单
            OrderDetail orderDetail = orderDetailMapper.selectOrderDetailByOrderNumber(orderNumber);
            if (orderDetail != null && "0".equals(orderDetail.getStatus())) {
                orderDetail.setStatus("1"); // 设置为支付
                orderDetail.setTransactionId(transactionId);
                orderDetail.setPayTime(new Date());
                orderDetailMapper.updateOrderDetail(orderDetail);
                log.info("订单{}支付成功，支付宝交易号：{}", orderNumber, transactionId);
            }
            sseServer.sendAllMessage();
            return "success";
        } catch (Exception e) {
            log.error("支付宝支付回调通知处理异常", e);
            return "failure";
        }
    }

    /**
     * 根据手机号查询订单列表
     */
    @GetMapping("/orders/list")
    @Anonymous
    public TableDataInfo getOrdersByTel(String tel, HttpServletRequest request,String orderNumber) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setTel(tel);
        orderDetail.setOrderNumber(orderNumber);
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token为空");
        }
        if (StringUtils.isNotEmpty(tel)||StringUtils.isNotEmpty(orderNumber)) {
            PageHelper.orderBy("pay_time desc");
            startPage();
            List<OrderDetail> orders = orderDetailMapper.selectOrderDetailList(orderDetail);
            return getDataTable(orders);
        }
        UserLogin userLogin2 = userLoginService.selectUserLoginByToken(token);
        if (Objects.isNull(userLogin2)) {
            throw new RuntimeException("未查询到该用户");
        }
        PageHelper.orderBy("pay_time desc");
        startPage();
        List<OrderDetail> orders = orderDetailMapper.selectOrderDetailByToken(userLogin2.getToken());
        return getDataTable(orders);
    }

    //添加订单
    @PostMapping("/addOrder")
    @Anonymous
    @Transient
    public AjaxResult addOrder(@RequestBody OrderDetail orderDetail, HttpServletRequest request, @RequestHeader(name = "token", required = true) String token) {
        String orderType = orderDetail.getOrderType();
        String payType = orderDetail.getPayType();
        String subTel = orderDetail.getTel();
        if (StringUtils.isEmpty(orderType) || StringUtils.isEmpty(payType)) {
            return error("orderType || payType 缺少值");
        }
        Map<String, String> map = new HashMap<>();
        String orderNumber = UUID.randomString(24);
        UserLogin userLogin = userLoginService.selectUserLoginByToken(token);
        if (StringUtils.isNotEmpty(orderDetail.getTel())) {
            if (StringUtils.isEmpty(userLogin.getTel())) {
                //根据手机号搜索token
                UserLogin userLogin2 = userLoginService.selectUserLoginByTel(orderDetail.getTel());
                if (Objects.nonNull(userLogin2)) {
                    map.put("token", userLogin2.getToken());
                    userLogin2.setUserKey(userLogin.getUserKey());
                    userLoginService.updateUserLogin(userLogin2);
                    Integer[] ids = new Integer[]{userLogin.getId()};
                    userLoginService.deleteUserLoginByIds(ids);
                } else {
                    userLogin.setTel(orderDetail.getTel());
                    userLoginService.updateUserLogin(userLogin);
                    map.put("token", userLogin.getToken());
                }
            } else {
                // 当前用户已经绑定手机号时
                // 判断提交的手机号和绑定的手机号是否相同
                if (!userLogin.getTel().equals(subTel.trim())) {
                    // 不相同就使用提交的手机号的token
                    UserLogin userLogin2 = userLoginService.selectUserLoginByTel(subTel);
                    if (null != userLogin2) {//提交的手机号存在用户
                        map.put("token", userLogin2.getToken());
                    } else {
                        // 新用户，创建登录记录
                        String resToken = UUID.fastUUID().toString();
                        userLogin = new UserLogin();
                        userLogin.setToken(resToken);
                        userLogin.setCreateTime(new Date());
                        userLogin.setTel(subTel);
                        userLoginService.insertUserLogin(userLogin);
                        map.put("token", resToken);
                    }
                }
                map.put("token", userLogin.getToken());
            }
        }else {
            map.put("token", token);
        }
        if (orderDetail.getFormSubId() > 0) {
            // 查询formSub是否存在
            FormSub formSub = formSubMapper.selectFormSubById(orderDetail.getFormSubId());
            if (formSub == null) {
                return error("未找到对应的表单数据");
            }
        }
        orderDetail.setOrderNumber(orderNumber);
        orderDetail.setUserKey(userLogin.getUserKey());
        orderDetail.setCreateTimeForm(new Date());
        orderDetail.setFormSubId(orderDetail.getFormSubId());
        orderDetail.setToken(map.get("token"));
        orderDetail.setCreateTime(new Date());
        orderDetailMapper.insertOrderDetail(orderDetail);
        map.put("orderNumber", orderNumber);
        return success(map);
    }

    /**
     * 添加表单提交记录
     */
    @PostMapping("/addFormSub")
    @Anonymous
    public AjaxResult addFormSub(@RequestBody FormSub formSub,
                                 HttpServletRequest request,
                                 @RequestHeader(name = "token", required = true) String token) {
        String subTel = formSub.getTel();
        // 校验手机号
        if (StringUtils.isEmpty(subTel)) {
            return error("手机号不能为空");
        }
        // 判断订单是否存在
        if (StringUtils.isNotEmpty(formSub.getOrderNumber()) &&
                Objects.isNull(orderDetailMapper.selectOrderDetailByOrderNumber(formSub.getOrderNumber()))) {
            return error("未找到对应的订单信息");
        }
        // 通过登录token判断用户是否存在
        UserLogin userLogin = userLoginService.selectUserLoginByToken(token);
        if (Objects.isNull(userLogin)) {
            return error("用户不存在");
        }
        // 判断当前登录用户是否绑定电话
        String tel = userLogin.getTel();
        String resToken = userLogin.getToken();
        if (StringUtils.isEmpty(tel)) {//用户未绑定手机号
            UserLogin userLogin2 = userLoginService.selectUserLoginByTel(subTel);
            if(Objects.nonNull(userLogin2)){
                resToken = userLogin2.getToken();
                userLogin2.setUserKey(userLogin.getUserKey());
                userLoginService.updateUserLogin(userLogin2);
                Integer[] ids = new Integer[]{userLogin.getId()};
                userLoginService.deleteUserLoginByIds(ids);
            }else {
                // 绑定当前用户手机号
                userLogin.setTel(formSub.getTel());
                userLoginService.updateUserLogin(userLogin);
                resToken = userLogin.getToken();
            }
        } else {
            // 当前用户已经绑定手机号时
            // 判断提交的手机号和绑定的手机号是否相同
            if (!tel.equals(subTel.trim())) {
                // 不相同就使用提交的手机号的token
                UserLogin userLogin2 = userLoginService.selectUserLoginByTel(subTel);
                if (null != userLogin2) {//提交的手机号存在用户
                    resToken = userLogin2.getToken();
                } else {
                    // 新用户，建登录记录
                    resToken = UUID.fastUUID().toString();
                    userLogin = new UserLogin();
                    userLogin.setToken(resToken);
                    userLogin.setCreateTime(new Date());
                    userLogin.setTel(subTel);
                    userLoginService.insertUserLogin(userLogin);
                }
            }
        }
        // 保存提交单
        formSub.setCreateTime(new Date());
        formSub.setToken(resToken);
        formSubMapper.insertFormSub(formSub);
        Map<String, Object> result = new HashMap<>();
        result.put("formSubId", formSub.getId());
        result.put("token", resToken);
        return success(result);
    }

    //查询企业列表
    @GetMapping("/getCompanyList")
    @Anonymous
    public AjaxResult getCompanyList(@RequestParam("keyword") String keyword, @RequestHeader(name = "token", required = true) String token) throws IOException {
        if (Objects.isNull(userLoginService.selectUserLoginByToken(token))) {
            return error("未查询到该用户");
        }
        String url = "https://businessfuzzy.shumaidata.com/getbusinessfuzzy";
        Map<String, String> params = new HashMap<>();
        params.put("keyword", keyword);
        String result = aliTools.get(appCode, url, params);
        JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");
        return success(jsonObject);
    }

    //微信小程序支付
    @PostMapping("/wxMiniPay")
    @Anonymous
    @Transient
    public AjaxResult wxMiniPayOrder(@Validated @RequestBody WxPayVo wxPayVo, HttpServletRequest request) throws Exception {
        //支付订单号
        String orderId = wxPayVo.getOrderNumber();
        OrderDetail orderDetail = orderDetailMapper.selectOrderDetailByOrderNumber(orderId);
        if (Objects.isNull(orderDetail)) {
            return error("订单不存在");
        }
        if (!orderDetail.getStatus().equals("0")) {
            return error("订单状态异常");
        }
        log.info("小程序支付订单号:{}", orderId);
        String ip = HttpUtils.getIpAddress(request);
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
        log.info("支付客户端ip:{}", ip);

        // 根据orderType询字典获取支付金额
        String orderType = orderDetail.getOrderType();
        if (StringUtils.isEmpty(orderType)) {
            return error("订单类型不能为空");
        }
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("h5_sys_orderprice");
        // 从字典服务获取金额
        SysDictData dictData = dictDataService.selectDictDataList(sysDictData)
                .stream()
                .filter(dict -> orderType.equals(dict.getDictValue()))
                .findFirst()
                .orElse(null);

        if (Objects.isNull(dictData)) {
            return error("未找到对应的订单金额配置");
        }
        BigDecimal amount;
        try {
            amount = new BigDecimal(dictData.getDictLabel()).divide(BigDecimal.valueOf(100));
        } catch (NumberFormatException e) {
            log.error("订单金额配格式错误", e);
            return error("订单金额配置错误");
        }

        // 调用微信小程序支付服务
        Map<String, String> payResult = weChatPayService.wxMiniPay(
                wxPayVo.getOpenId(),  // 需要在WxPayVo中添加openId字段
                orderDetail.getBusinessName(),
                orderId,
                amount.multiply(BigDecimal.valueOf(100)).intValue(),
                ip,
                wxJsapiPayCallback
        );
        orderDetailMapper.updateAmountById(convertToCents(amount.intValue()), amount, orderDetail.getId());

        if (payResult == null || payResult.isEmpty()) {
            return AjaxResult.error("微信支付下单失败,请稍后重试");
        }

        Map<String, String> map = new HashMap<>();
        map.put("payParams", JSONObject.toJSONString(payResult));
        map.put("tel", orderDetail.getTel());
        map.put("orderId", orderId);
        sseServer.sendAllMessage();
        return AjaxResult.success(map);
    }

    @GetMapping("/getConfig")
    @Anonymous
    public AjaxResult getConfig() {
        Map<String, Object> configMap = new HashMap<>();

        // 获取所有的字典类型
        List<SysDictType> dictTypes = dictTypeService.selectDictTypeList(null);

        // 获取平台名称 - 从h5_sys_name字典类型获取
        SysDictType nameDict = dictTypes.stream()
                .filter(type -> "h5_sys_name".equals(type.getDictType()))
                .findFirst()
                .orElse(null);

        if (nameDict == null) {
            return AjaxResult.error("未找到必要的H5配置信息");
        }

        configMap.put("name", nameDict.getDictName());

        // 获取订单类型配置
        List<Map<String, Object>> orderTypes = new ArrayList<>();
        SysDictData queryOrderType = new SysDictData();
        queryOrderType.setDictType("h5_sys_ordertype");
        queryOrderType.setStatus("0"); // 只获取正常状态的数据

        List<SysDictData> orderTypeList = dictDataService.selectDictDataList(queryOrderType);
        for (SysDictData orderType : orderTypeList) {
            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("label", orderType.getRemark());
            typeMap.put("value", orderType.getDictValue());

            // 获取对应的原价
            SysDictData originalPrice = dictDataService.selectDictDataList(new SysDictData())
                    .stream()
                    .filter(dict -> "h5_sys_originalprice".equals(dict.getDictType())
                            && orderType.getDictValue().equals(dict.getDictValue())
                            && "0".equals(dict.getStatus()))
                    .findFirst()
                    .orElse(null);

            // 获取对应的订单价格
            SysDictData orderPrice = dictDataService.selectDictDataList(new SysDictData())
                    .stream()
                    .filter(dict -> "h5_sys_orderprice".equals(dict.getDictType())
                            && orderType.getDictValue().equals(dict.getDictValue())
                            && "0".equals(dict.getStatus()))
                    .findFirst()
                    .orElse(null);

            // 如果价格未配置则设为0
            typeMap.put("originalprice", originalPrice != null ?
                    originalPrice.getDictLabel() : 0);
            typeMap.put("orderprice", orderPrice != null ?
                    orderPrice.getDictLabel() : 0);

            orderTypes.add(typeMap);
        }
        configMap.put("orderType", orderTypes);

        // 获取所有h5_sys_开头的字典类型并组装数据
        for (SysDictType dictType : dictTypes) {
            if (dictType.getDictType().startsWith("h5_sys_")
                    && !"h5_sys_ordertype".equals(dictType.getDictType())
                    && !"h5_sys_originalprice".equals(dictType.getDictType())
                    && !"h5_sys_orderprice".equals(dictType.getDictType())) {

                List<Map<String, Object>> dictDataList = new ArrayList<>();
                SysDictData query = new SysDictData();
                query.setDictType(dictType.getDictType());
                query.setStatus("0"); // 只获取正常状态的数据

                List<SysDictData> dataList = dictDataService.selectDictDataList(query);
                for (SysDictData data : dataList) {
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("label", data.getRemark());
                    dataMap.put("value", data.getDictValue());
                    dictDataList.add(dataMap);
                }

                // 如果是支付类型，需要特殊处理
                if ("h5_sys_paytype".equals(dictType.getDictType())) {
                    configMap.put("payType", dictDataList);
                } else {
                    configMap.put(dictType.getDictType(), dictDataList);
                }
            }
        }
        return AjaxResult.success(configMap);
    }

    /**
     * 查询企业信息
     */
    @GetMapping("/tax/querycompany")
    @Anonymous
    public AjaxResult queryCompany(@RequestParam("keyword") String keyword) {
        try {
            String url = "http://nj.bcwl3.com/api/tax/querycompany?keyword=" + URLEncoder.encode(keyword, "UTF-8");
            String result = HttpUtils.sendGet(url,null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            return success(jsonObject);
        } catch (Exception e) {
            log.error("查询企业信息失败", e);
            return error("查询企业信息失败");
        }
    }

}
